package com.example.controller;

import com.example.entity.Goods;
import com.example.entity.Goodstype;
import com.example.service.GoodstypeService;
import com.example.service.impl.GoodsServiceImpl;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
import javax.annotation.Resource;
import java.util.ArrayList;

@Api(value = "商品控制器",description = "zhes商品控制器")
@Controller
@RequestMapping("/admin")
public class GoodsCtrl {
    @Resource
    GoodsServiceImpl goodsService;

    @Resource
    GoodstypeService goodstypeService;

    @ApiOperation(value = "获取所有商品",notes = "获取所有商品")
    @RequestMapping(value = "/goods",method = {RequestMethod.POST,RequestMethod.GET})
    public String getGoodsList(Model model,
                               @RequestParam(value = "pageNum",required = false,defaultValue = "2") Integer pageNum,
                               @RequestParam(value = "pageSize",required = false,defaultValue = "3") Integer pageSize){
        PageInfo<Goods> goodsListPage=goodsService.queryAll(pageNum,pageSize);
        model.addAttribute("goodsListPage",goodsListPage);
        return "goodsList";
    }
    @ApiOperation("根据ID删除商品")
    @GetMapping("/delGoods/{id}")
    public String delGoods(@PathVariable("id") int id, Model model) {
        int num = goodsService.deleteById(id);
        model.addAttribute("msg","删除成功！");
        return "forward:/admin/goods";
    }
    //forward 转发
    @GetMapping("/goods/{id}")
    public String getGoodsById(@PathVariable("id") int id,Model model){
        Goods goods = goodsService.findById(id);
        model.addAttribute("goods",goods);

        // 获取商品类别
        ArrayList<Goodstype> goodstypesList = goodstypeService.findAll();
        model.addAttribute("goodstypesList",goodstypesList);
        return "goodsEdit";
    }

    @PostMapping("/editGoods")
    public String editGoods(Goods goods,Model model) {
        int num =  goodsService.update(goods);

        model.addAttribute("msg","添加成功");
        return "forward:/admin/goods";
    }
    @GetMapping("/gotoAddGoods")
    public String gotoAddGoods(Model model){
        // 获取商品类别
        ArrayList<Goodstype> goodstypesList = goodstypeService.findAll();
        model.addAttribute("goodstypesList",goodstypesList);
        return "goodsAdd";
    }

    @PostMapping("/addGoods")
    public String addGoods(Goods goods){
        // 进行商品信息的保存
        int num = goodsService.insert(goods);
        return "forward:/admin/goods";
    }
    @GetMapping("/test")
    public Goods test(){
        return new Goods();
    }
}
